import { nodeResolve } from '@rollup/plugin-node-resolve';
import babel from '@rollup/plugin-babel';
import commonjs from '@rollup/plugin-commonjs';
import { terser } from 'rollup-plugin-terser';
import globals from 'rollup-plugin-node-globals';
import clear from 'rollup-plugin-clear';
import fs from 'fs';
import path from 'path';

const modulesPath = path.join(__dirname, 'src', 'modules');
const dirs = fs.readdirSync(path.join(__dirname, 'src', 'modules'), {
  encoding: 'utf-8',
});
let allInputFile = [];
dirs.forEach((dir) => {
  const files = fs.readdirSync(path.join(modulesPath, dir), {
    encoding: 'utf-8',
  });
  allInputFile = allInputFile.concat(
    files
      .filter((item) => item.indexOf('index.js') < 0)
      .map((item) => ({
        path: path.join(modulesPath, dir, item),
        filename: item,
        name: item.replace(/\.js$/, ''),
      }))
  );
});

const plugins = [
  clear({
    targets: ['dist'],
  }),
  globals(),
  nodeResolve(),
  commonjs(),
  terser(),
  babel({
    exclude: 'node_modules/**',
    babelHelpers: 'bundled',
  }),
];

// const external = allInputFile.map((item) => "./" + item.name);

const configs = [
  {
    input: './src/index.js',
    output: [
      {
        file: './dist/index.js',
        format: 'umd',
        name: 'index',
      },
    ],
    plugins,
  },
];

allInputFile.forEach((file) => {
  configs.push({
    input: file.path,
    output: [
      {
        file: `./dist/${file.name}.js`,
        format: 'umd',
        name: file.name,
      },
    ],
    plugins,
  });
});

export default configs;
